// 轮播图功能
class Slider {
    constructor(container) {
        this.slider = container.querySelector('.slider');
        this.slides = container.querySelectorAll('.slide');
        this.dots = container.querySelectorAll('.dot');
        this.currentIndex = 0;
        this.interval = null;
        this.touchStartX = 0;
        this.touchEndX = 0;
        
        this.init();
    }
    
    init() {
        this.startAutoPlay();
        this.addEventListeners();
    }
    
    startAutoPlay() {
        this.interval = setInterval(() => this.nextSlide(), 1500);
    }
    
    nextSlide() {
        this.currentIndex = (this.currentIndex + 1) % this.slides.length;
        this.updateSlider();
    }
    
    prevSlide() {
        this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length;
        this.updateSlider();
    }
    
    updateSlider() {
        this.slider.style.transform = `translateX(-${this.currentIndex * 33.333333}%)`;
        
        this.dots.forEach((dot, index) => {
            dot.classList.toggle('active', index === this.currentIndex);
        });
    }
    
    resetInterval() {
        clearInterval(this.interval);
        this.startAutoPlay();
    }
    
    handleTouchStart(e) {
        this.touchStartX = e.changedTouches[0].screenX;
        clearInterval(this.interval);
    }
    
    handleTouchEnd(e) {
        this.touchEndX = e.changedTouches[0].screenX;
        this.handleSwipe();
        this.startAutoPlay();
    }
    
    handleSwipe() {
        if (this.touchEndX < this.touchStartX - 50) {
            this.nextSlide();
        } else if (this.touchEndX > this.touchStartX + 50) {
            this.prevSlide();
        }
    }
    
    addEventListeners() {
        this.dots.forEach((dot, index) => {
            dot.addEventListener('click', () => {
                this.currentIndex = index;
                this.updateSlider();
                this.resetInterval();
            });
        });
        
        this.slider.addEventListener('mouseenter', () => {
            clearInterval(this.interval);
        });
        
        this.slider.addEventListener('mouseleave', () => {
            this.startAutoPlay();
        });
        
        this.slider.addEventListener('touchstart', (e) => this.handleTouchStart(e));
        this.slider.addEventListener('touchend', (e) => this.handleTouchEnd(e));
    }
}

// 商品加载功能
class ProductLoader {
    constructor(containerId) {
        this.container = document.getElementById(containerId);
        this.products = [];
    }
    
    async loadProducts() {
        try {
            const response = await fetch('../data/products.json');
            this.products = await response.json();
            this.renderProducts();
            this.addCartEventListeners();
        } catch (error) {
            console.error('加载商品失败:', error);
            this.showError();
        }
    }
    
    renderProducts() {
        this.container.innerHTML = this.products.map(product => `
            <div class="product-card">
                <img src="../images/${product.image}" alt="${product.name}" class="product-image">
                <div class="product-info">
                    <h3 class="product-title">${product.name}</h3>
                    <div>
                        <span class="product-price">¥${product.price}</span>
                        <span class="original-price">¥${product.originalPrice}</span>
                    </div>
                    <button class="add-to-cart" data-id="${product.id}">加入购物车</button>
                </div>
            </div>
        `).join('');
    }
    
    addCartEventListeners() {
        document.querySelectorAll('.add-to-cart').forEach(button => {
            button.addEventListener('click', (e) => {
                const productId = e.target.getAttribute('data-id');
                this.addToCart(productId);
            });
        });
    }
    
    addToCart(productId) {
        const product = this.products.find(p => p.id === productId);
        if (!product) return;
        
        let cart = JSON.parse(localStorage.getItem('cart')) || [];
        const existingItem = cart.find(item => item.id === productId);
        
        if (existingItem) {
            existingItem.quantity += 1;
        } else {
            cart.push({
                id: product.id,
                name: product.name,
                price: product.price,
                image: product.image,
                quantity:   1
            });
        }
        
        localStorage.setItem('cart', JSON.stringify(cart));
        this.showNotification(`${product.name} 已添加到购物车`);
    }
    
    showNotification(message) {
        const notification = document.createElement('div');
        notification.className = 'notification show';
        notification.textContent = message;
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.classList.add('fade-out');
            setTimeout(() => {
                notification.remove();
            }, 500);
        }, 2000);
    }
    
    showError() {
        this.container.innerHTML = `
            <div class="error-message">
                <p>加载商品失败，请稍后再试</p>
                <button onclick="location.reload()">重新加载</button>
            </div>
        `;
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    // 初始化轮播图
    const sliderContainer = document.querySelector('.slider-container');
    if (sliderContainer) {
        new Slider(sliderContainer);
    }
    
    // 加载商品
    const productContainer = document.getElementById('productContainer');
    if (productContainer) {
        const productLoader = new ProductLoader('productContainer');
        productLoader.loadProducts();
    }
});